<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/6/25
 * Time: 16:53
 */
namespace app\admin\controller;
use \think\Request;
use think\Db;
use app\common\model\Area as AreaModel;
class Member extends \app\admin\controller\Base
{
    protected $res = array(
        'index'   => array('css' => '2,3,4', 'js' => 'list,My97DatePicker'),
        'fabu'   => array('css' => '2,3,4', 'js' => 'list,My97DatePicker'),
        'buy'   => array('css' => '2,3,4', 'js' => 'list,My97DatePicker'),
    );

    /**
     * 首页数据
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index(){
        $state = input('state');
        $sheng = input('sheng');
        $shi = input('shi');
        $qu = input('qu');
        $keywords= input('keywords');
        $login_start = input('login_start');
        $login_end = input('login_end');
        $register_start = input('register_start');
        $register_end = input('register_end');
        $type = input('type');
        $attestation = input('attestation');
        $map = [];

        if($state&&$state!=''){
            $map['u.user_status'] = $state;
        }
        if($type&&$type!=''){
            $map['u.user_type'] = $type;
        }
        if($attestation&&$attestation!=''){
            $map['user_attestation'] = $attestation;
        }
        if($sheng&&$sheng!=""){
            $map['us.district_id'] = $sheng;
            $whereCity['pid'] = $sheng;
        }else{
            $whereCity['pid'] = '';
        }
        if($shi&&$shi!=""){
            $map['ui.district_id'] = $shi;
            $whereDistrict['pid'] = $shi;
        }else{
            $whereDistrict['pid'] = '';
        }
        if($qu&&$qu!=""){
            $map['uq.district_id'] = $qu;
        }
        if($keywords&&$keywords!=""){
            $map['u.user_id|u.user_username|u.user_phone'] = ['like',"%" . $keywords . "%"];
        }
        if($login_start&&$login_start!==""&&$login_end=="")
        {
            $map['u.user_time'] = ['>= time',$login_start];
        }
        if($login_end&&$login_end!==""&&$login_start=="")
        {
            $map['u.user_time'] = ['<= time',$login_end];
        }
        if($login_start&&$login_start!==""&&$login_end&&$login_end!=="")
        {
            $map['u.user_time'] = ['between time',[$login_start,$login_end]];
        }
        if($register_start&&$register_start!==""&&$register_end=="")
        {
            $map['u.user_last_login'] = ['>= time',$register_start];
        }
        if($register_end&&$register_end!==""&&$register_start=="")
        {
            $map['u.user_last_login'] = ['<= time',$register_end];
        }
        if($register_start&&$register_start!==""&&$register_end&&$register_end!=="")
        {
            $map['u.user_last_login'] = ['between time',[$register_start,$register_end]];
        }
        $AreaModel = new AreaModel();
        $page = input('param.page');
        $list = Db::table('up_u_user')
            ->alias ('u')
            ->where($map)
            ->join('up_area us','us.district_id=u.user_sheng','left')
            ->join('up_area ui','ui.district_id=u.user_shi','left')
            ->join('up_area uq','uq.district_id=u.user_qu','left')
            ->field('u.user_id,u.user_type,u.user_username,u.user_phone,u.user_image,u.user_time,u.user_last_login,u.user_status,us.district sheng,ui.district shi,uq.district qu,u.user_attestation')
            ->order('u.user_time desc')
            ->paginate(15);
        if(!$page){
            $pages = 0;
        }else{
            $pages = $page-1;
        }
        $wherePro['pid'] = 1;
        $action = '/' . Request::instance()->controller() . '/' . Request::instance()->action();
        $province =$AreaModel->selectArea($wherePro);
        if($sheng&&$sheng!=""){
            $city =$AreaModel->selectArea($whereCity);
        }else{
            $city =[];
        }
        if($shi&&$shi!=""){
            $district =$AreaModel->selectArea($whereDistrict);
        }else{
            $district = [];
        }
        $this->assign ([
            'page'=>$page,
            'list'=>$list,
            'pages'=>$pages,
            'province' => $province,
            'city' => $city,
            'district' => $district,
            'action'=>$action,
            'state'=>$state,
            'sheng'=>$sheng,
            'shi'=>$shi,
            'qu'=>$qu,
            'keywords'=>$keywords,
            'login_start'=>$login_start,
            'login_end'=>$login_end,
            'register_start'=>$register_start,
            'register_end'=>$register_end,
            'type'=>$type,
            'attestation'=>$attestation
        ]);
        return $this->fetch();
    }

    /**
     * 查询市
     */
    public function city(){
        $city = $_POST['city'];
        $cityArray = Db::table('up_area')->where('pid',$city)->select();
        $data['cityArray'] = $cityArray;
        return json($data);
    }

    /**
     * 查询区
     */
    public function area(){
        $area = $_POST['area'];
        $cityArray = Db::table('up_area')->where('pid',$area)->select();
        $data['cityArray'] = $cityArray;
        return json($data);
    }

    /**
     * @return \think\response\Json
     * 修改用户状态
     */
    public function UpdateUser(){
        $ids = strtoarray(input('post.ids'));
        $act = input('post.act');
        $token = md5(date('YmdHis') . rand(100000,999999));
        foreach ($ids as $key => $vo) {
            $result = Db::table('up_u_user')->where('user_id',$vo)->update(['user_status'=>$act,'user_update_time'=>date('Y-m-d H:i:s'),'user_token'=>$token]);
        }
        if ($result) {
            return $this->api_success('操作成功');
        } else {
            return $this->api_dbError();
        }
    }

    /**
     * look 查看个人信息
     * @return html
     */
    public function look(){
        $data = Db::table('up_u_user')
            ->where('user_id',input('id'))
            ->field('user_id,user_username,user_phone,user_image,user_gender,user_status,user_app_count')
            ->find();
        $auth  = Db::table('up_user_auth')
            ->where(['uauth_user_id'=>input('id'),'uauth_status'=>1])
            ->field('uauth_type')
            ->select();
        $auth = array_column ($auth,'uauth_type');
        for($i=0;$i<count($auth);$i++){
            switch($auth[$i]){
                case 2:
                    $auth[$i]='铜牌';
                   break;
                case 3:
                    $auth[$i]='银牌';
                    break;
                case 4:
                    $auth[$i]='金牌';
                    break;
            }
        }
        $data['auth'] = implode('、',$auth);
        $this->assign ('data',$data);
        return $this->fetch('information');
    }

    /**
     * buy 购买记录
     * @return html
     */
    public function buy(){
        $user_id = input('id');
        $data = Db::table('up_order')
            ->alias('uo')
            ->join('up_user_auth_long al','uo.order_long_id=al.long_id','left')
            ->where(['order_user_id'=>$user_id])
            ->field('uo.order_id,uo.order_datetime,uo.order_long_type,uo.order_money,al.long_how,uo.order_status,uo.order_type')
            ->order('uo.order_datetime desc')
            ->paginate(15,false, [
                'query' => request()->param(),
            ]);
        $this->assign ('list',$data);
        return $this->fetch('record');
    }

    /**
     * fabu 发布的记录
     * @return html
     */
    public function fabu(){
        $data = Db::table('up_article')
            ->where('a_user_id',input('id'))
            ->field('a_id,a_title,a_createtime,a_num,a_image,a_content')
            ->paginate(15,false, [
                'query' => request()->param(),
            ]);
        $page = input('param.page');
        if(!$page){
            $pages = 0;
        }else{
            $pages = $page-1;
        }
        $this->assign ([
            'page'=>$page,
            'list'=>$data,
            'pages'=>$pages,
        ]);
        return $this->fetch('fabu');
    }

    /**
     * 导出用户信息
     * @return \think\response\Json
     */
    public function excel(){
        $state = input('state');
        $sheng = input('sheng');
        $shi = input('shi');
        $qu = input('qu');
        $keywords= input('keywords');
        $login_start = input('login_start');
        $login_end = input('login_end');
        $register_start = input('register_start');
        $register_end = input('register_end');
        $map = [];
        if($state&&$state!=''){
            $map['u.user_status'] = $state;
        }
        if($sheng&&$sheng!=""){
            $map['us.district_id'] = $sheng;
            $whereCity['pid'] = $sheng;
        }else{
            $whereCity['pid'] = '';
        }
        if($shi&&$shi!=""){
            $map['ui.district_id'] = $shi;
            $whereDistrict['pid'] = $shi;
        }else{
            $whereDistrict['pid'] = '';
        }
        if($qu&&$qu!=""){
            $map['uq.district_id'] = $qu;
        }
        if($keywords&&$keywords!=""){
            $map['u.user_id|u.user_username|u.user_phone'] = ['like',"%" . $keywords . "%"];
        }
        if($login_start&&$login_start!==""&&$login_end=="")
        {
            $map['u.user_time'] = ['>= time',$login_start];
        }
        if($login_end&&$login_end!==""&&$login_start=="")
        {
            $map['u.user_time'] = ['<= time',$login_end];
        }
        if($login_start&&$login_start!==""&&$login_end&&$login_end!=="")
        {
            $map['u.user_time'] = ['between time',[$login_start,$login_end]];
        }
        if($register_start&&$register_start!==""&&$register_end=="")
        {
            $map['u.user_last_login'] = ['>= time',$register_start];
        }
        if($register_end&&$register_end!==""&&$register_start=="")
        {
            $map['u.user_last_login'] = ['<= time',$register_end];
        }
        if($register_start&&$register_start!==""&&$register_end&&$register_end!=="")
        {
            $map['u.user_last_login'] = ['between time',[$register_start,$register_end]];
        }
        $result = Db::table('up_u_user')
            ->alias ('u')
            ->where($map)
            ->join('up_area us','us.district_id=u.user_sheng','left')
            ->join('up_area ui','ui.district_id=u.user_shi','left')
            ->join('up_area uq','uq.district_id=u.user_qu','left')
            ->field ('u.user_username,u.user_phone,u.user_time,u.user_last_login,us.district sheng,ui.district shi,uq.district qu,u.user_status')
            ->select();
        for($i=0;$i<count($result);$i++){
            if($result[$i]['user_status'] == 1){
                $result[$i]['user_status'] = '正常';
            }else{
                $result[$i]['user_status'] = '冻结';
            }
        }
        $xlsCell  = array(
            array('user_username','昵称'),
            array('user_phone','手机号'),
            array('user_time','注册时间'),
            array('user_last_login','上次登录时间'),
            array('sheng','省'),
            array('shi','市'),
            array('qu','区'),
            array('user_status','状态'),
        );
        $data = $this->exportExcel($xlsCell,$result);
        return $data;
    }

    /**
     * 添加虚拟用户
     * @return mixed|\think\response\Json
     */
    public function add(){
        if(request()->isAjax ()){
            extract(input());
            if($username == "" ){
                return $this->api_error('用户名不能为空', '14001');
            }
            if($phone == ""){
                return $this->api_error('手机号不能为空', '14001');
            }
            if(!preg_match("/^1[34578]{1}\d{9}$/",$phone)){
                return $this->api_error('请输入正确的手机号', '14001');
            }
            $arr = Db::table('up_u_user')->where('user_phone',$phone)->find();
            if(!empty($arr)){
                return $this->api_error('手机号已被注册', '14001');
            }
            if($_FILES['file']['name'][0]!='') {
                $info = $this->uploadFile($_FILES);
                $param['user_image'] =$info;

            }
            $param['user_username'] = $username;
            $param['user_phone'] = $phone;
            $param['user_app_count'] = $this->getAcount();
            $param['user_time'] = date('Y-m-d H:i:s');
            $param['user_type'] = 2;
            $res = Db::table('up_u_user')->insert($param);
            if ($res) {
                return $this->api_success("操作成功");
            } else {
                return $this->api_dbError("操作失败");
            }
        }
        return $this->fetch('add');
    }

    public function check(){
        if(request()->isAjax ()){
            extract(input());
            if($type == 'pass'){
                $attestation = 2;
                $title = "认证信息审核通过";
                $msg = '恭喜！您提交的商家认证信息已经通过审核，快去购买召集令吧';
                $type = 6;
            }else{
                $attestation = 3;
                $title="认证信息审核不通过";
                $msg = "很遗憾！您提交的商家认证信息没有通过审核，您可以重新进行申请";
                $type = 7;
            }
            $param = [
                'n_title'=>$title,
                'n_content'=>$msg,
                'n_createtime'=>date('Y-m-d H:i:s'),
                'n_type'=>$type,
                'n_send_type'=>2,
                'n_user_id'=>$id,
                'n_read_users'=>',0,',
                'n_clear_users'=>',0,',
                'n_status'=>1
            ];
            // 启动事务
            Db::startTrans();
            try{
                Db::table('up_u_user')->where('user_id',$id)->setField ('user_attestation',$attestation);
                Db::table('up_notice')->insert($param);
                // 提交事务
                Db::commit();
                $this->Jpush("$id", $title, 1, ['type'=>1]);
                return $this->api_success("操作成功");
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->api_dbError("操作失败");
            }
        }
        $id = input('id');
        $data = Db::table('up_u_user')
            ->where('user_id',$id)
            ->field('user_id,user_rel_name,user_att_phone,user_att_add,user_identity_image,user_identity_side,user_business_image,user_attestation')
            ->find();
        $this->assign ('res',$data);
        return $this->fetch('check');
    }
}